//
//  MyRunViewController.m
//  享动
//
//  Created by lanou on 16/4/7.
//  Copyright © 2016年 HHUI. All rights reserved.
//

#import "MyRunViewController.h"
#import "MyRunTableViewCell.h"
#import "RequestManager.h"
#import "MyRunModel.h"
#import "MyRunDetailViewController.h"
#import <MJRefresh.h>
#import "NetWorkState.h"
#import "AppDelegate.h"
#import "MyRun+CoreDataProperties.h"

@interface MyRunViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, assign) NSInteger oldY;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) NSMutableArray *modelArray;

// 转圈圈的控件
@property (nonatomic, strong) UIActivityIndicatorView *activity;

// 上拉加载更多的参数
@property (nonatomic, assign) NSInteger p;

// 请求数据时候的参数
@property (nonatomic, strong) NSString *requestAge;

// 数据加载视图
@property (nonatomic, strong) UIImageView *animationImageView;

// 网络超时视图
@property (nonatomic, strong) UIView *hint;

// 临时数据库
@property (nonatomic, strong) NSManagedObjectContext *context;

@end

@implementation MyRunViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    _context = delegate.managedObjectContext;
    
    self.navigationItem.title = @"健身食谱";
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT + 49) style:UITableViewStylePlain];
    [_tableView registerClass:[MyRunTableViewCell class] forCellReuseIdentifier:@"cell"];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    // 滚动圈圈视图
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [_activity setCenter:CGPointMake(KWIDTH / 2, KHEIGHT / 2 - 30)];
    [self.tableView addSubview:_activity];
    
    

    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        // 加载更多
        [_activity startAnimating];
        [self loadMoreData];
    }];
    
    // 判断有没有网络
    if ([[NetWorkState shareInstance]reachability])
    {
        // 网络请求
        [self request];
        // 正在加载的动画
        [self addLoadingHint];
        
    } else
    {
        // 网络超时的画面
        [self addHint];
    }
    

}

#pragma mark ---- 没有网络的提示框 ----
- (void)addHint
{
    // 没有网络的提示框
    _hint = [[UIView alloc]initWithFrame:CGRectMake(KWIDTH / 4, KHEIGHT / 2 - KHEIGHT / 15, KWIDTH / 2, KHEIGHT / 15 * 2)];
    _hint.backgroundColor = [UIColor blackColor];
    _hint.alpha = 0.7;
    _hint.layer.cornerRadius = 10;
    [self.view addSubview:_hint];
    
    UIImageView *noNetworkimageView = [[UIImageView alloc]initWithFrame:CGRectMake(_hint.frame.size.width / 3 + 3, 0, _hint.frame.size.width / 3 + 3, _hint.frame.size.width / 3 * 53 / 63)];
    noNetworkimageView.image = [UIImage imageNamed:@"noNetwork"];
    [_hint addSubview:noNetworkimageView];
    
    UILabel *hintLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, _hint.frame.size.height / 2, KWIDTH / 2, _hint.frame.size.height / 2)];
    hintLabel.text = @"网络超时";
    hintLabel.textAlignment = NSTextAlignmentCenter;
    hintLabel.textColor = [UIColor whiteColor];
    [_hint addSubview:hintLabel];
    
    [self performSelector:@selector(removeHint) withObject:nil afterDelay:3];
    
}

- (void)removeHint
{
    [_hint removeFromSuperview];
}

#pragma mark  --- 正在加载的时候的动画 -----
- (void)addLoadingHint
{
    _animationImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KWIDTH / 3, KHEIGHT / 2 - KHEIGHT / 15, KWIDTH / 3, KHEIGHT / 15 * 2)];
    NSMutableArray *imageArray = [NSMutableArray array];
    for (int i = 0; i<= 7; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"loaded_%02d.png", i]];
        [imageArray addObject:image];
    }
    _animationImageView.animationImages = imageArray;
    _animationImageView.animationDuration = 0.1 * imageArray.count;
    _animationImageView.animationRepeatCount = FLT_MAX;
    [_animationImageView startAnimating];
    [self.view addSubview:_animationImageView];
}

#pragma mark --- 网络请求 ---
- (void) request
{
    _p = 1;
    
    _requestAge = @"%E7%98%A6%E8%BA%AB%E9%A4%90";
    
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://ibaby.ipadown.com/api/food/food.show.list.php?age=%@&p=%ld&pagesize=12&order=views", _requestAge,(long)_p] requestType:RequestTypePost parDic:nil finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *resultsArray = [dataDic objectForKey:@"results"];
        
        _modelArray = [NSMutableArray array];
        for (NSDictionary *dic in resultsArray)
        {
            MyRun *myrun = [NSEntityDescription insertNewObjectForEntityForName:@"MyRun" inManagedObjectContext:_context];
            MyRunModel *model = [[MyRunModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            myrun.image = model.thumb_2;
            myrun.name = model.title;
            [_context save:nil];
            [_modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
            [_activity stopAnimating];
            [_animationImageView removeFromSuperview];
        });
        
    } error:^(NSError *error) {
        NSLog(@"菜谱网络请求错误");

    }];
}

#pragma mark --- 上拉加载更多 ---
- (void)loadMoreData
{
    [_activity startAnimating];
    _p += 1;
    _requestAge = @"%E7%98%A6%E8%BA%AB%E9%A4%90";
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://ibaby.ipadown.com/api/food/food.show.list.php?age=%@&p=%@&pagesize=12&order=views", _requestAge,[NSNumber numberWithInteger:_p]] requestType:RequestTypePost parDic:nil finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *resultsArray = [dataDic objectForKey:@"results"];
        
        for (NSDictionary *dic in resultsArray)
        {
            MyRunModel *model = [[MyRunModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_modelArray addObject:model];
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
            [_activity stopAnimating];
            // 请求结束之后 停止刷新  这样才能执行下次的上拉刷新
            [_tableView.mj_footer endRefreshing];
        });
        
    } error:^(NSError *error) {
        NSLog(@"菜谱网络请求错误");
        [_tableView.mj_footer endRefreshing];
    }];
}

#pragma mark --- tableView行数 ---
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([[NetWorkState shareInstance]reachability])
    {
        return [_modelArray count];
    }
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MyRun"];
    NSArray *array = [_context executeFetchRequest:request error:nil];
    return [array count];
}

#pragma mark --- tableView分区个数 ---
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark --- tableViewCell ---
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MyRun"];
    NSArray *array = [_context executeFetchRequest:request error:nil];

    MyRunTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
  
    if (array != nil)
    {
        if (indexPath.row <= array.count - 1)
        {
            MyRun *model = array[indexPath.row];
            [cell setCEllByMyRun:model];
        }
        MyRunModel *model = _modelArray[indexPath.row];
        [cell setCellByModel:model];
    }
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark --- 点击cell触发的方法 ---
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyRunDetailViewController *myRunVc = [[MyRunDetailViewController alloc] init];
    MyRunModel *model = _modelArray[indexPath.row];
    myRunVc.ID = model.ID;
    [self.navigationController pushViewController:myRunVc animated:YES];
}

#pragma mark --- 返回每行高度 ---
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}

#pragma mark --- 当scrollView 将要滑动的时候 ---
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _oldY = scrollView.contentOffset.y;
}

#pragma mark --- 当scrollView 正在滑动的时候 ---
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if( scrollView.contentOffset.y > _oldY)
    {
        // 向下滑动
        [UIView transitionWithView:self.navigationController.tabBarController.tabBar duration:0.5 options:UIViewAnimationOptionCurveEaseIn animations:^{
            self.navigationController.tabBarController.tabBar.frame = CGRectMake(0, KHEIGHT, KWIDTH, 49);
        } completion:nil];
    }
    else
    {
        // 向上滑动
        [UIView transitionWithView:self.navigationController.tabBarController.tabBar duration:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
            self.navigationController.tabBarController.tabBar.frame = CGRectMake(0, KHEIGHT - 49, KWIDTH, 49);
        } completion:nil];

    }
}

/*
- (void) viewWillAppear:(BOOL)animated
{
    self.navigationController.tabBarController.tabBar.hidden = YES;
}

- (void) viewWillDisappear:(BOOL)animated
{
    self.navigationController.tabBarController.tabBar.hidden = NO;
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
